/*
 * Copyright (c) 2012, Alex Gittemeier, All Rights Reserved.
 *
 *  Simple Xml is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Simple Xml is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Simple Xml.  If not, see <http://www.gnu.org/licenses/>.
 */
package gbc.xml.simple;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// TODO: Auto-generated Javadoc
/**
 * Container class for XML tag information.
 * <p>
 * Be aware that <b>tagName</b> and <b>text</b> are trimmed during parsing, so
 * do not rely on whitespace at the beginning or end of text.
 */
public class XmlTag {

	/** The tag name. */
	public String tagName = "";

	/** The text. */
	public String text = "";

	/** The list of enclosed tags. */
	public List<XmlTag> enclosedTags = new ArrayList<XmlTag>();

	/** The list of attributes. */
	public Map<String, String> attributes = new HashMap<String, String>();

	/**
	 * Returns a crude representation of the XmlTag.
	 * 
	 * @return the string
	 */
	@Override
	public String toString() {
		return "<" + tagName + " " + attributes + ">\n" + text + enclosedTags
				+ "\n</" + tagName + ">\n";
	}

	void trimStrings() { // Package scope
		tagName = tagName.trim();
		text = text.trim();
	}

	/**
	 * Picks out tags whose root <b>tagName</b> (not inside <b>enclosedTags</b>)
	 * is equivalent to the supplied tagName.
	 * 
	 * @param tagList
	 *            The list to filter.
	 * @param tagName
	 *            The name to filter by.
	 * @return a list of all the tags that match the supplied criterion.
	 */
	public static List<XmlTag> getTagsByName(List<XmlTag> tagList,
			String tagName) {
		List<XmlTag> ret = new ArrayList<XmlTag>();
		for (XmlTag curTag : tagList) {
			if (curTag.tagName == tagName)
				ret.add(curTag);
		}
		return ret;
	}

	/**
	 * Picks out the first tag whose root <b>tagName</b> (not inside
	 * <b>enclosedTags</b>) is equivalent to the supplied tagName.
	 * 
	 * @param tagList
	 *            The list to filter.
	 * @param tagName
	 *            The name to filter by.
	 * @return The first tag that matches the supplied criterion, or null if tag
	 *         could not be found.
	 */
	public static XmlTag getFirstTagByName(List<XmlTag> tagList, String tagName) {
		List<XmlTag> ret = getTagsByName(tagList, tagName);
		if (ret.size() != 0)
			return ret.get(0);
		return null;
	}
}
